import cv2 as cv

# 测试能否使用树莓派的摄像头模块
import importlib
try:
    picam2 = importlib.import_module('picamera2')
except ModuleNotFoundError:
    USE_PICAMERA2 = False
else:
    USE_PICAMERA2 = True

USE_PICAMERA2 = True

if USE_PICAMERA2:
    picap = picam2.Picamera2()
else:
    cvcap = cv.VideoCapture()

CAMERA_IS_OPENED = False

def openCamera():
    global CAMERA_IS_OPENED
    if CAMERA_IS_OPENED: return
    if USE_PICAMERA2:
        cfg = picap.create_video_configuration(main={"size": (1920,1080),'format':'BGR888'}, lores={"size": (640, 480)}, display="main")
        picap.configure(cfg)
        picap.start()
    else:
        cvcap.open(0,cv.CAP_V4L2)
    CAMERA_IS_OPENED = True

def captureImage():
    if USE_PICAMERA2:
        array = picap.capture_array()
        if type(array) != type(None):
            return cv.cvtColor(array,cv.COLOR_RGBA2BGR)
        else:
            return None
    else:
        _,array = cvcap.read()
        return array
